package com.itheima.tanhua.dubbo.mongo.api.impl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.tanhua.api.UserLikeApi;
import com.itheima.tanhua.mongo.UserLike;
import com.itheima.tanhua.vo.CountsVo;
import com.itheima.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Lff
 * @date 2022/4/1
 */
@DubboService
public class UserLikeApiImpl implements UserLikeApi {
    @Autowired
    private MongoTemplate mongo;

    /**
     * 添加或修改喜欢关系
     *
     * @param userLike
     */
    @Override
    public Boolean saveOrUpdate(UserLike userLike) {
        try {
            Criteria exists = Criteria.where("userId").is(userLike.getUserId())
                    .and("likeUserId").is(userLike.getLikeUserId());
            UserLike one = mongo.findOne(Query.query(exists), UserLike.class);
            userLike.setUpdated(System.currentTimeMillis());
            //没有数据 直接保存
            if (one == null) {
                userLike.setCreated(System.currentTimeMillis());
                mongo.save(userLike);
                return true;
            }
            //有数据
            Update update = new Update();
            update.set("isLike", userLike.getIsLike());
            update.set("updated", userLike.getUpdated());
            //修改
            mongo.updateFirst(Query.query(Criteria.where("id").is(one.getId())),
                    update, UserLike.class);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 用户是否相互喜欢
     *
     * @param userId
     * @param likeUserId
     * @return
     */
    @Override
    public boolean hasLikeRelation(Long userId, Long likeUserId) {
        Criteria criteria1 = Criteria.where("userId").is(userId)
                .and("likeUserId").is(likeUserId).and("isLike").is(true);

        Criteria criteria2 = Criteria.where("userId").is(likeUserId)
                .and("likeUserId").is(userId).and("isLike").is(true);

        boolean exists1 = mongo.exists(Query.query(criteria1), UserLike.class);
        boolean exists2 = mongo.exists(Query.query(criteria2), UserLike.class);

        return exists1 && exists2;
    }


    @Override
    public CountsVo findCounts(Long id) {
        //根据id查喜欢的数量
        Query q1 = Query.query(Criteria.where("userId").is(id).and("isLike").is(true));
        List<UserLike> userLikes = new ArrayList<>();
        userLikes = mongo.find(q1, UserLike.class);
        //根据id查粉丝的数量
        List<UserLike> userLikes1 = new ArrayList<>();
        Query q2 = Query.query(Criteria.where("likeUserId").is(id).and("isLike").is(true));
        userLikes1 = mongo.find(q2, UserLike.class);
        //根据id查互相喜欢的数量
        //抽取likeUserId
        List<Long> ids = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        int count = 0;
        for (Long uid : ids) {
            Criteria c = Criteria.where("userId").is(uid).and("likeUserId").is(id).and("isLike").is(true);
            if (mongo.exists(Query.query(c), UserLike.class)) {
                count++;
            }
        }
        CountsVo countsVo = new CountsVo();
        countsVo.setLoveCount(userLikes.size());
        countsVo.setFanCount(userLikes1.size());
        countsVo.setEachLoveCount(count);
        return countsVo;
    }


    /**
     * 查询 根据指定Userid查询UserLike
     * 返回PageResult
     * <p>
     * 1-互相关注
     * <p>
     * 2-我关注
     * <p>
     * 3-粉丝
     *
     * @param userId   当前登录用户id
     * @param type     查询类型
     * @param page     页码
     * @param pagesize 页尺寸
     * @return
     */
    @Override
    public PageResult findUserLikePage(Long userId, Integer type, Integer page, Integer pagesize) {
        PageResult pr = new PageResult();
        if (type == 1) {
            //1-互相关注
            Criteria criteria = Criteria.where("userId").is(userId)
                    .and("alreadyLove").is(true);
            //构造条件
            Query focusQuery = Query.query(criteria).with(Sort.by(Sort.Order.desc("created")))
                    .skip((page - 1) * pagesize)
                    .limit(pagesize);
            //查询
            List<UserLike> focus = mongo.find(focusQuery, UserLike.class);
            pr.setItems(focus);
            pr.setPage(page);
            pr.setPagesize(pagesize);
            pr.setCounts(Long.valueOf(focus.size()));
        } else if (type == 2) {
            //2-我喜欢
            Query like = Query.query(Criteria.where("userId").is(userId).and("isLike").is(true))
                    .with(Sort.by(Sort.Order.desc("created")))
                    .skip((page - 1) * pagesize)
                    .limit(pagesize);
            List<UserLike> userLikes = mongo.find(like, UserLike.class);
            pr.setItems(userLikes);
            pr.setPage(page);
            pr.setPagesize(pagesize);
            pr.setCounts(Long.valueOf(userLikes.size()));
        } else if (type == 3) {
            //3-粉丝
            Query fans = Query.query(Criteria.where("likeUserId").is(userId).and("isLike").is(true))
                    .with(Sort.by(Sort.Order.desc("created")))
                    .skip((page - 1) * pagesize)
                    .limit(pagesize);
            List<UserLike> userFans = mongo.find(fans, UserLike.class);
            pr.setItems(userFans);
            pr.setPage(page);
            pr.setPagesize(pagesize);
            pr.setCounts(Long.valueOf(userFans.size()));
        }
        return pr;
    }

    /**
     * 更改用户喜欢状态
     *
     * @param userId
     * @param likeUserId
     * @param isAlreadyLove
     */
    @Override
    public void updateAlreadyLove(Long userId, Long likeUserId, boolean isAlreadyLove) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("likeUserId").is(likeUserId);
        Criteria criteria1 = Criteria.where("userId").is(likeUserId)
                .and("likeUserId").is(userId);
        Query query = Query.query(criteria);
        Query query1 = Query.query(criteria1);
        Update update = new Update();
        update.set("alreadyLove", isAlreadyLove);
        //修改数据
        mongo.updateFirst(query, update, UserLike.class);
        mongo.updateFirst(query1, update, UserLike.class);
    }
}
